package com.lyf.service;

import com.lyf.dao.BackendUserDao;
import com.lyf.dao.DevUserDao;
import com.lyf.dto.LoginDto;
import com.lyf.entity.BackendUser;
import com.lyf.entity.DevUser;
import com.lyf.sys.SysConstant;
import com.lyf.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lyf.utils.SessionUtils;

import java.util.List;
import java.util.UUID;

@Service
public class LoginService {

    @Autowired
    DevUserDao devUserDao;
    @Autowired
    BackendUserDao backendUserDao;

    public LoginUserVo login(LoginDto loginDto) {

        LoginUserVo vo = new LoginUserVo();

        if (loginDto.getUserType() == SysConstant.UserTypeInt.admin) {

            BackendUser backendUser = new BackendUser();
            backendUser.setUsercode(loginDto.getAccount());
            backendUser.setUserpassword(loginDto.getPassword());
            List<BackendUser> list = backendUserDao.queryAllBy(backendUser);

            if(list == null){
                throw new RuntimeException("账号密码错误");
            }

            vo.setAccount(backendUser.getUsercode());
            vo.setUserType(SysConstant.UserTypeStr.admin);

            StringBuffer token = new StringBuffer();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            token.append(uuid+"-");
            token.append(vo.getAccount()+"-");
            token.append(System.currentTimeMillis()+"-");
            token.append(vo.getUserType());

            vo.setToken(token.toString());

            SessionUtils.put(token.toString(),list.get(0));

        } else if (loginDto.getUserType() == SysConstant.UserTypeInt.dev) {

            DevUser devUser = new DevUser();
            devUser.setDevcode(loginDto.getAccount());
            devUser.setDevpassword(loginDto.getPassword());
            List<DevUser> list = devUserDao.queryAllBy(devUser);

            if(list == null||list.size()==0){
                throw new RuntimeException("账号密码错误");
            }

            vo.setAccount(devUser.getDevcode());
            vo.setUserType(SysConstant.UserTypeStr.dev);

            StringBuffer token = new StringBuffer();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            token.append(uuid+"-");
            token.append(vo.getAccount()+"-");
            token.append(System.currentTimeMillis()+"-");
            token.append(vo.getUserType());

            vo.setToken(token.toString());

            SessionUtils.put(token.toString(),list.get(0));


        }else{
            throw new RuntimeException("用户类型错误！");
        }

        return vo;
    }
}
